import vue from '@/main.js';

var ossReturnArr = [];
var resultData = {
  ossReturnArr:[],
  code:0,
}
var source = ""
var otherParams ={
  orderId:'',
  jobseekerId:0,
  recruitUnitId:0,
}
//参数一  File数组
//参数二：例如  contracts/thisorderId/
//参数三：例如  /order-management/contract
//1上传文件到oss并将信息提交到数据库
export const submitUpload = function (fileList, filePath, sourcePage2, otherParams2) {
  return new Promise((resolve, reject) => {
    source = sourcePage2;
    otherParams = otherParams2;
    
    if (fileList.length == 0) {
      vue.$message.error("请先选择文件，再提交到云端");
      return "false";
    }

    //设置加载进度条
    const loading = vue.$loading({
      lock: true,
      text: '文件上传中',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 创建FormData对象用于文件上传
    let formData = new FormData();
    let file = fileList[0]; // 先处理单文件上传
    formData.append('file', file);
    
    // 添加其他参数
    if (filePath) {
      formData.append('filePath', filePath);
    }
    if (source) {
      formData.append('source', source);
    }
    if (otherParams && otherParams.used) {
      formData.append('used', otherParams.used);
    }
    if (otherParams && otherParams.jobseekerId && otherParams.jobseekerId != 0) {
      formData.append('jobseekerId', otherParams.jobseekerId);
    }
    if (otherParams && otherParams.recruitUnitId && otherParams.recruitUnitId != 0) {
      formData.append('recruitUnitId', otherParams.recruitUnitId);
    }

    // 使用后端上传接口
    vue.$axios.post("/file/upload", formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(res => {
      if (res.code === 200) {
        vue.$message.success("文件上传成功");
        loading.close();
        resultData.code = 200;
        resolve(resultData);
      } else {
        vue.$message.error("文件上传失败: " + (res.msg || '未知错误'));
        loading.close();
        resultData.code = res.code || 500;
        resultData.msg = res.msg || '未知错误';
        reject(resultData);
      }
    }).catch(error => {
      vue.$message.error("文件上传失败: " + error.message);
      loading.close();
      resultData.code = 500;
      resultData.msg = error.message;
      reject(resultData);
    });
  });
}

//2上传文件到oss但不将信息提交到数据库（使用批量上传接口替代）
export const uploadNoSubmitMysql = function (fileList, filePath, sourcePage2, otherParams2) {
  return new Promise((resolve, reject) => {
    source = sourcePage2;
    otherParams = otherParams2;
    
    if (fileList.length == 0) {
      vue.$message.error("请先选择文件，再提交到云端");
      return "false";
    }

    //设置加载进度条
    const loading = vue.$loading({
      lock: true,
      text: '文件上传中',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 创建FormData对象用于批量文件上传
    let formData = new FormData();
    
    // 添加所有文件
    fileList.forEach(file => {
      formData.append('files', file);
    });
    
    // 添加其他参数
    if (filePath) {
      formData.append('filePath', filePath);
    }
    if (source) {
      formData.append('source', source);
    }
    if (otherParams && otherParams.used) {
      formData.append('used', otherParams.used);
    }
    if (otherParams && otherParams.jobseekerId && otherParams.jobseekerId != 0) {
      formData.append('jobseekerId', otherParams.jobseekerId);
    }
    if (otherParams && otherParams.recruitUnitId && otherParams.recruitUnitId != 0) {
      formData.append('recruitUnitId', otherParams.recruitUnitId);
    }

    // 使用后端批量上传接口
    vue.$axios.post("/file/batchUpload", formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(res => {
      if (res.code === 200) {
        vue.$message.success("文件上传成功");
        loading.close();
        resultData.code = 200;
        resultData.ossReturnArr = res.data;
        resolve(resultData);
      } else {
        vue.$message.error("文件上传失败: " + (res.msg || '未知错误'));
        loading.close();
        resultData.code = res.code || 500;
        resultData.msg = res.msg || '未知错误';
        reject(resultData);
      }
    }).catch(error => {
      vue.$message.error("文件上传失败: " + error.message);
      loading.close();
      resultData.code = 500;
      resultData.msg = error.message;
      reject(resultData);
    });
  });
}

//文件信息提交数据库
export const commitDrawing = function () {

  console.log("this.ossReturn" , ossReturnArr);
  if (ossReturnArr.length == 0) {
    vue.$message.error("请先选取文件上传到云端，再保存信息");
    return;
  }
console.log('ossReturnArrzzzzzzzzzzzzzzzzzz' , ossReturnArr)

   return vue.$axios.post("/aliyunOss/addList", ossReturnArr).then((res) => {
     console.log('resdddddddddd' , res)
    if (res.code == 200) {
      vue.$message.success("数据保存成功");
      console.log('44444455555555')
      console.log('res.dat44444a', res)
      resultData.ossReturnArr = res.data;
      console.log('resultData.ossReturnArr', resultData.ossReturnArr)
      ossReturnArr = [];
    } else {
      vue.$message.error("数据保存失败，请联系管理员");
    }
  });


  //清空临时信息
  //this.initUpload();
}

//文件下载
export const fileDownLoad = function (fileId) {
  if (!fileId) {
    vue.$message.error("文件ID不能为空");
    return;
  }
  
  // 创建一个临时的a标签用于下载
  const link = document.createElement('a');
  link.href = vue.$axios.defaults.baseURL + '/file/download/' + fileId;
  link.target = '_blank';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

//文件预览
export const filePreview = function (fileId) {
  if (!fileId) {
    vue.$message.error("文件ID不能为空");
    return;
  }
  
  // 获取文件预览URL
  return vue.$axios.get("/file/view/" + fileId).then(res => {
    if (res.code === 200 && res.data && res.data.url) {
      // 使用返回的OSS临时URL直接打开
      window.open(res.data.url, '_blank');
      return res.data;
    } else {
      vue.$message.error("获取文件预览URL失败");
      return null;
    }
  }).catch(error => {
    vue.$message.error("获取文件预览URL失败: " + error.message);
    return null;
  });
}
